package o2o.web.actions.postman;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.JYPageUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.agent.PostmanAgentRelationMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanShopRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.PostmanShopRelation;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.system.data.POSTMAN_IN_CITY_OR_AGENT_DATA;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.shop.ShopMan;
import o2o.web.actions.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * create by yangtk
 * time :2018/11/09
 * des :店铺管理配送员 配送员与店铺为多对多关系（紫燕再用）
 */
@Controller
public class ShopPostManAction {

    // 获取该店铺下的所有配送员
    @RequestMapping("/shop/postman/list")
    @ResponseBody
    public String getPostManByShopId(String token, Long shopId, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        ShopInfo shopInfo = null;
        // 管理员可以看
        if (User.hasAdminAuth(user.getUserType())) {
            if (ValidateUtil.isID(shopId)) {
                shopInfo = ShopMemory.getInstance().getShopById(shopId);
            } else {
                shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
            }
            if (null == shopInfo) {
                return AjaxResult.errorResult("该店铺已不存在，请核实");
            }
        } else {
            // 普通店铺只能查看自己的配送员
            shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
            if (null == shopInfo) {
                return AjaxResult.errorResult("该店铺已不存在，请核实");
            }
        }
        if (!ValidateUtil.isAbsInteger(page)) {
            page = 1;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }
        List<CityPostman> list = PostmanShopRelationMemory.getInstance().getShopPostManListByShopUsername(shopInfo.getOwnUsername());
        if (ValidateUtil.isAbsList(list)) {
            if (size >= 1000) {
                List<CityPostmanVO> voList = list.stream().map(item -> {
                    return converPostmanTo(item);
                }).collect(Collectors.toList());
                return AjaxResult.successResult(voList, voList.size());
            } else {
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                    List<CityPostmanVO> voList = ((List<CityPostman>) pageList.list).stream().map(item -> {
                        return converPostmanTo(item);
                    }).collect(Collectors.toList());
                    return AjaxResult.successResult(voList, pageList.totalCount);
                }
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    // 获取配送员到店铺
    @RequestMapping("/postman/shop/service/list")
    @ResponseBody
    public String getServiceShopByPostMan(String token, String postmanUsername, Integer page, Integer size, String city, String key) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限管理");
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return AjaxResult.errorResult("配送员账号不能为空");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == postman) {
            return AjaxResult.errorResult("该配送员已不存在，请核实");
        }
        if (!ValidateUtil.isAbsInteger(page)) {
            page = 1;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }
        List<ShopInfo> shopInfos = PostmanShopRelationMemory.getInstance().getShopListByPostmanUsername(postmanUsername);
        if (ValidateUtil.isAbsList(shopInfos)) {
            shopInfos = shopInfos.stream().filter(item -> {
                if (ValidateUtil.isNotNull(city) && !city.equals(item.getCity())) {
                    return false;
                }
                if (ValidateUtil.isNotNull(key) && !(Optional.ofNullable(item.getShopName()).orElse("").contains(key))) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(shopInfos)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfos, page, size);
                if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                    return AjaxResult.successResult(pageList.list, pageList.totalCount);
                }
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    // 获取指定配送员未服务的店铺
    @RequestMapping("/postman/shop/unservice/list")
    @ResponseBody
    public String getUnServiceShopByPostMan(String token, String postmanUsername, Integer page, Integer size, String city, String key) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限管理");
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return AjaxResult.errorResult("配送员账号不能为空");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == postman) {
            return AjaxResult.errorResult("该配送员已不存在，请核实");
        }
        List<ShopInfo> list = PostmanShopRelationMemory.getInstance().getShopListByPostmanUsername(postmanUsername);
        Map<Long, ShopInfo> map = new HashMap<>();
        if (ValidateUtil.isAbsList(list)) {
            map = list.stream().collect(Collectors.toMap(ShopInfo::getId, Function.identity()));
        }
        List<ShopInfo> shopInfos = null;
        if (SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT != null && SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT) {
            Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(postmanUsername);
            shopInfos = ShopMan.listOfAgentId(agentId, key);
        } else {
            shopInfos = ShopMemory.getInstance().list();
            if (ValidateUtil.isAbsList(shopInfos)) {
                shopInfos = shopInfos.stream().filter(item -> {
                    if (ValidateUtil.isNotNull(city) && !city.equals(item.getCity())) {
                        return false;
                    }
                    if (ValidateUtil.isNotNull(key) && !(Optional.ofNullable(item.getShopName()).orElse("").contains(key))) {
                        return false;
                    }
                    return true;
                }).collect(Collectors.toList());
            }
        }
        if (ValidateUtil.isAbsList(shopInfos)) {
            Map<Long, ShopInfo> finalMap = map;
            shopInfos = shopInfos.stream().filter(item -> finalMap.get(item.getId()) == null).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(shopInfos)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfos, page, size);
                if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                    return AjaxResult.successResult(pageList.list, pageList.totalCount);
                }
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    // 添加店铺配送员的关系
    @RequestMapping("/postman/shop/service/add")
    @ResponseBody
    public String addServiceShopByPostMan(String token, String postmanUsername, String shopIds) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限管理");
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return AjaxResult.errorResult("配送员账号不能为空");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == postman) {
            return AjaxResult.errorResult("该配送员已不存在，请核实");
        }
        if (ValidateUtil.isNull(shopIds)) {
            return AjaxResult.errorResult("请选择店铺");
        }
        List<ShopInfo> list = PostmanShopRelationMemory.getInstance().getShopListByPostmanUsername(postmanUsername);
        Map<Long, ShopInfo> map = new HashMap<>();
        if (ValidateUtil.isAbsList(list)) {
            for (ShopInfo shopInfo : list) {
                map.put(shopInfo.getId(), shopInfo);
            }
        }

        List<Long> shopIdList1 = getListShopId(shopIds);
        List<Long> ShopIdList = new ArrayList<>();
        if (ValidateUtil.isAbsList(shopIdList1)) {
            for (Long l : shopIdList1) {
                if (map.get(l) != null) {
//                    ShopIdList.remove(l);
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(l);
                if (null == shopInfo) {
//                    ShopIdList.remove(l);
                    continue;
                }
                ShopIdList.add(l);
            }
        }
        // 需要执行的sql
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(ShopIdList)) {
            for (Long l : ShopIdList) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(l);
                if (null == shopInfo) {
                    continue;
                }
                PostmanShopRelation p = get_PostmanShopRelation(shopInfo, postman, user.getUsername());
                try {
                    UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_SHOP_RELATION, p, conn);
                } catch (Exception e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(conn);        // 回滚
                    UserDaoSql.getInstance().close(conn);
                    return AjaxResult.errorResult("操作失败，请稍后重试");
                }
            }
        }
        try {
            conn.commit(); // 提交
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 缓存
        PostmanShopRelationMemory.getInstance().run();
        return AjaxResult.successResult();
    }

    // del店铺配送员的关系
    @RequestMapping("/postman/shop/service/del")
    @ResponseBody
    public String deleteServiceShopByPostMan(String token, String postmanUsername, String shopIds) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限管理");
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return AjaxResult.errorResult("配送员账号不能为空");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == postman) {
            return AjaxResult.errorResult("该配送员已不存在，请核实");
        }
        if (ValidateUtil.isNull(shopIds)) {
            return AjaxResult.errorResult("请选择店铺");
        }
        List<Long> shopIdList = getListShopId(shopIds);
        if (shopIdList == null || shopIdList.size() < 1) {
            return AjaxResult.errorResult("店铺解析失败");
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        List<ShopInfo> shopInfos = new ArrayList<>();
        if (ValidateUtil.isAbsList(shopIdList)) {
            for (Long l : shopIdList) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(l);
                if (null != shopInfo) {
                    shopInfos.add(shopInfo);
                }
            }
        }
        List<Long> relationId = new ArrayList<>();
        if (ValidateUtil.isAbsList(shopInfos)) {
            for (ShopInfo shopInfo : shopInfos) {
                PostmanShopRelation p = PostmanShopRelationMemory.getInstance().getPostmanShopList(cityPostman.getUsername(), shopInfo.getOwnUsername());
                if (null == p) {
                    continue;
                }
                relationId.add(p.getId());
            }
        }
        // 需要执行的sql
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(relationId)) {
            for (Long l : relationId) {
                StringBuffer sb = new StringBuffer();
                sb.append("update ").append(PojoTables.POSTMAN_SHOP_RELATION).append(" set delFlag = 1 ").append(" where id=").append(l);
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
                } catch (Exception e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(conn);        // 回滚
                    UserDaoSql.getInstance().close(conn);
                    return AjaxResult.errorResult("操作失败，请稍后重试");
                }
            }
        }

        try {
            conn.commit(); // 提交业务
//            UserDaoSql.getInstance().close(conn);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 缓存
        PostmanShopRelationMemory.getInstance().run();

        return AjaxResult.successResult();
    }

    private PostmanShopRelation get_PostmanShopRelation(ShopInfo shopInfo, CityPostman postman, String createUser) {
        PostmanShopRelation p = new PostmanShopRelation();
        p.setDelFlag(0);
        p.setPostmanId(postman.getId());
        p.setPostmanUsername(postman.getUsername());
        p.setShopId(shopInfo.getId());
        p.setShopUsername(shopInfo.getOwnUsername());
        p.setCreateUser(createUser);
        p.setCreateTime(DateUtils.getCurrTime());
        return p;
    }

    private List<Long> getListShopId(String ids) {
        List<Long> list = new ArrayList<>();
        String str[] = ids.trim().split(",");
        for (String s : str) {
            try {
                Long l = Long.parseLong(s);
                list.add(l);
            } catch (Exception e) {
                System.out.println("类型转换错误");
                e.printStackTrace();
            }
        }
        return list;
    }


    private CityPostmanVO converPostmanTo(CityPostman item) {
        CityPostmanVO vo = new CityPostmanVO();
        BeanUtils.copyProperties(item, vo);
        UserInfo info = UserInfoMemory.getInstance().getUserInfo(item.getUsername());
        if (info != null) {
            vo.setName(info.getName());
            vo.setSignPhoto(info.getSignPhoto());
            if (ValidateUtil.isNotNull(info.getSignPhoto()) && ValidateUtil.isNotNetUrl(info.getSignPhoto())) {
                vo.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + info.getSignPhoto());
            }
        }
        vo.setTelPhone(info.getTelPhone());
        return vo;
    }


}


